<?php

class TFItemImage {

	function __construct() {
		//$this->auth = new UserAccount;
		$this->error_str = '';
	}

	// Untested function (probably bad design also)...
	public static function GetImageFromFieldArray($image_r) {
		$temp_image = new TFItemImage();
		//$this->image = $image_r;
		$temp_image->image = $image_r;
		return $temp_image;
	}

	// Untested function (probably bad design also)...
	public static function GetImageFromKey($imageID) {
		global $udb;
		
		$image_ar = $udb->GetResultsAsNestedArray("SELECT * FROM tfItemImage WHERE imageID = ".$imageID."");
		$image_r = $image_ar[0];

		//$this->image = $image_r;
		return TFItemImage::GetImageFromFieldArray($image_r);
	}


	public static function CreateThumbnail($imageID, $image_url) {
		global $udb;
		$MAX_DIMENSION = 150;

		// Make sure source file is a .jpg.
		if (strtolower(substr($image_url, -4)) != ".jpg") {
			return false;
		}

		// Open source file from internet.
		$source_image = imagecreatefromjpeg($image_url);
		//echo "size: " . imagesx($source_image) . "," . imagesy($source_image);

		// Calculate new dimensions.
		$source_width = imagesx($source_image);
		$source_height = imagesy($source_image);
		if ($source_width > $source_height) {
			$thumb_width = $MAX_DIMENSION;
			$thumb_height = $MAX_DIMENSION * ($source_height / $source_width);
		}
		else {
			$thumb_width = $MAX_DIMENSION * ($source_width / $source_height);
			$thumb_height = $MAX_DIMENSION;
		}

		// Create resized image.
		$thumb_image = imagecreatetruecolor($thumb_width, $thumb_height);
		imagecopyresampled($thumb_image, $source_image, 0, 0, 0, 0, $thumb_width, $thumb_height, imagesx($source_image), imagesy($source_image));


		// Find/create destination location
		$THUMB_ROOT_PATH = $_SERVER['DOCUMENT_ROOT'].'/storage/itemimagethumbs150/';
		$thousand_folder = round($imageID, -3);
		// Make thousand folder if it doesn't exist.
		mkdir($THUMB_ROOT_PATH . $thousand_folder);
		$thumb_path = $THUMB_ROOT_PATH . $thousand_folder . "/" . $imageID . ".jpg";

		// ?

		// Write thumb file.
		imagejpeg($thumb_image, $thumb_path);

		// Mark record as thumb-exists.
		$udb->SendQuery("UPDATE tfItemImage SET thumb150Exists = 1, imageWidth = " . $source_width . ", imageHeight = " . $source_height . " WHERE imageID = " . $imageID . ";");

		return true;
	}


}

?> 
